def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    # 检查行、列、对角线是否有赢家
    for i in range(3):
        if all([cell == player for cell in board[i]]):  # 检查行
            return True
        if all([board[j][i] == player for j in range(3)]):  # 检查列
            return True
    if board[0][0] == board[1][1] == board[2][2] == player:  # 检查主对角线
        return True
    if board[0][2] == board[1][1] == board[2][0] == player:  # 检查副对角线
        return True
    return False

def is_board_full(board):
    for row in board:
        if " " in row:
            return False
    return True

def get_move(player):
    while True:
        move = input(f"玩家 {player}，请输入你的移动（行和列，例如 '1 2'）：")
        try:
            row, col = map(int, move.split())
            if 1 <= row <= 3 and 1 <= col <= 3:
                return row - 1, col - 1
            else:
                print("输入的行或列超出范围，请重新输入。")
        except ValueError:
            print("输入格式不正确，请重新输入。")

def tic_tac_toe():
    board = [[" " for _ in range(3)] for _ in range(3)]
    current_player = "X"

    while True:
        print_board(board)
        row, col = get_move(current_player)

        if board[row][col] == " ":
            board[row][col] = current_player
            if check_winner(board, current_player):
                print_board(board)
                print(f"恭喜玩家 {current_player} 获胜！")
                break
            elif is_board_full(board):
                print_board(board)
                print("游戏结束，平局！")
                break
            else:
                current_player = "O" if current_player == "X" else "X"
        else:
            print("该位置已被占用，请选择其他位置。")

if __name__ == "__main__":
    tic_tac_toe()